<!-- 角色编辑弹窗 -->
<template>
  <el-drawer :visible="drawerEditBoolen"
             size="50%"
             :before-close="handleClose"
             ref="drawer">
    <template v-slot:title>
      <span class="hLabel">{{ isUpdate ? '修改优惠券' : '添加优惠券' }}</span>
    </template>
    <div class="ele-body">
      <el-card shadow="never">
        <el-form ref="form"
                 :model="form"
                 :rules="rules"
                 label-width="100px">
          <el-form-item label="卡券类型:"
                        prop="discountCouponType">
            <el-radio-group v-model="form.discountCouponType">
              <el-radio :disabled="this.isUpdate?form.discountCouponType == 1 ? false : true:false"
                        :label="1"
                        :value="1">满减</el-radio>
              <!-- <el-radio :label="2" value="2">折扣</el-radio> -->
              <el-radio :disabled="this.isUpdate?form.discountCouponType == 1 ? true : false:false"
                        :label="3"
                        :value="3">新用户</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="卡券名称:"
                        label-width="120px"
                        prop="cardRollName">
            <el-input clearable
                      :label-width="120"
                      :maxlength="100"
                      v-model="form.cardRollName"
                      placeholder="请输入卡券名称" />
          </el-form-item>
          <el-form-item label="卡券优惠面值:"
                        label-width="120px"
                        prop="cardRollAmount">
            <el-input clearable
                      :maxlength="100"
                      min="0"
                      type="number"
                      v-model.number="form.cardRollAmount"
                      placeholder="请输入卡券面值">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="最低使用额度:"
                        label-width="120px"
                        prop="howMuchAvailable">
            <el-input clearable
                      :maxlength="100"
                      min="0"
                      type="number"
                      v-model.number="form.howMuchAvailable"
                      placeholder="请最低使用额度">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="排序值:"
                        label-width="120px"
                        prop="sort">
            <span slot="label">
              排序值
              <el-tooltip placement="top">
                <div slot="content"> 用于前端展示排序， 值越大排在前面 </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <el-input clearable
                      min="0"
                      type="number"
                      :maxlength="20"
                      v-model.number="form.sort"
                      placeholder="请输入排序值" />
          </el-form-item>
          <el-form-item v-if="form.discountCouponType == 1"
                        label="卡券数量:"
                        label-width="120px"
                        prop="discountCouponNumber">
            <el-input-number v-model="form.discountCouponNumber"
                             :min="1"
                             :max="1000"
                             label="卡券数量"></el-input-number>
          </el-form-item>
          <el-form-item label="是否推荐:"
                        label-width="120px"
                        prop="notShow">
            <el-switch v-model="form.whetherToRecommend"
                       :active-value="1"
                       :inactive-value="2">
            </el-switch>
          </el-form-item>

          <el-form-item v-if="form.discountCouponType == 1"
                        label="领取时间:"
                        label-width="120px"
                        prop="start_time">

            <el-date-picker v-model="form.dateRange"
                            type="datetimerange"
                            :picker-options="pickerOptions"
                            unlink-panels
                            :default-time="['00:00:00', '23:59:59']"
                            range-separator="-"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy-MM-ddTHH:mm:ss"
                            class="ele-fluid" />
          </el-form-item>
          <el-form-item v-if="form.discountCouponType == 3"
                        label="有效期:"
                        label-width="120px"
                        prop="start_time">
            <el-date-picker v-model="form.timeValue"
                            type="date"
                            placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="卡券描述:"
                        label-width="120px"
                        prop="couponDescription">
            <el-input class="textareaHeight"
                      type="textarea"
                      clearable
                      :maxlength="100"
                      resize="none"
                      v-model="form.couponDescription"
                      placeholder="请输入卡券描述" />
          </el-form-item>
          <div class="drawer__footer">
            <el-button round
                       type="plain"
                       @click="handleClose"
                       size="medium">返回</el-button>
            <el-button type="primary"
                       round
                       :loading="loading"
                       size="medium"
                       @click="save">提交</el-button>
          </div>
        </el-form>
      </el-card>
    </div>
  </el-drawer>
</template>

<script>
// import TinymceEditor from '@/components/TinymceEditor/index.vue';
import {
  cardRollInsert,
  cardRollModify
} from '@/api/couponManagement/couponList/index';

export default {
  name: 'RoleEdit',
  components: {},
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object,
    drawerEditBoolen: Boolean
  },
  data () {
    const DEFAULT_FORM = {
      // 卡券名字
      cardRollName: '',
      // 卡券类型
      discountCouponType: 3,
      // 卡券面值
      cardRollAmount: '',
      // 卡券数量
      discountCouponNumber: 1,
      // 满多少可用
      howMuchAvailable: '',
      // 卡券排序
      sort: '',
      // 卡券描述
      couponDescription: '',
      //   是否推荐
      whetherToRecommend: true,
      // 日期范围选择
      dateRange: [],
      timeValue: '',
      //   站点id
      siteId: this.$store.state.site.info.id
    };
    return {
      options: [],
      images: [],
      showEdit: false,
      // 表单数据
      form: { ...DEFAULT_FORM },
      formArr: [],

      sumbitForm: {},
      // 日期时间选择器快捷项
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一个月',
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近三个月',
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      },
      // 表单验证规则
      rules: {
        money: [
          {
            required: true,
            message: '请输入充值金额',
            trigger: 'blur'
          }
        ],
        cardRollAmount: [{
          required: true,
          message: '请输入卡券优惠面值',
          trigger: 'blur'
        }],
        howMuchAvailable: [{
          required: true,
          message: '请输入请最低使用额度',
          trigger: 'blur'
        }],

        only: [
          {
            required: true,
            message: '请输入实付金额',
            trigger: 'blur'
          }
        ],
        sort: [
          {
            required: true,
            message: '请输入排序值',
            trigger: 'blur'
          }
        ]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      showChoose: false
    };
  },
  methods: {
    /* 保存编辑 */
    // 新增
    save () {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return false;
        }
        this.loading = true;
        for (const key in this.form) {
          if (key == 'dateRange') {
            if (this.form[key]?.length) {
              console.log(this.form[key].length);
              let startTime = this.form[key]?.[0];
              let endTime = this.form[key]?.[1];
              this.sumbitForm['periodValidityStart'] =
                startTime == undefined ? '' : startTime;
              this.sumbitForm['periodValidityEnd'] =
                endTime == undefined ? '' : endTime;
            }
          } else if (key == 'timeValue') {

            if (this.form[key]) {
              let endTime = this.form[key];
              this.sumbitForm['periodValidityEnd'] =
                endTime == undefined ? '' : endTime;
            }
          } else {
            this.sumbitForm[key] = this.form[key];
          }
        }

        console.log(this.sumbitForm);

        const saveOrUpdate = this.isUpdate ? cardRollModify : cardRollInsert;
        saveOrUpdate(this.sumbitForm)
          .then((msg) => {
            console.log(msg);
            this.loading = false;
            this.$message.success(msg);
            if (!this.isUpdate) {
              this.$router.go(0);
            }
            this.handleClose();
            this.$emit('done');
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      });
    },
    // 关闭抽屉
    handleClose () {
      console.log('查看详情');
      this.$emit('update:drawerEditBoolen', false);
    }
  },
  watch: {
    drawerEditBoolen (visible) {
      this.$nextTick(() => {
        if (visible) {
          console.log(this.data);
          if (this.data) {
            this.form.id = this.data.id;
            this.$util.assignObject(this.form, {
              ...this.data
            });
            if (this.data.discountCouponType == 1) {
              this.form.dateRange = [
                this.data.periodValidityStart,
                this.data.periodValidityEnd
              ];
            } else {
              this.form.timeValue = this.data.periodValidityEnd;
            }

            this.isUpdate = true;
          } else {
            this.isUpdate = false;
            this.form.dateRange = []
            this.form.timeValue = ''
          }
        } else {
          this.$nextTick(() => {
            this.$refs['form'].resetFields();
            console.log(this.form);
          });
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.foodsDiv div {
  margin-left: 20px;
  margin-top: 10px;
}
.hLabel {
  margin: 10px 0 20px;
  font-weight: 700;
  &::before {
    content: '';
    display: inline-block;
    vertical-align: top;

    margin-right: 5px;
    height: 23px;
    width: 6px;
    background-color: #1e6ceb;
  }
}
/deep/ .el-textarea__inner {
  height: 150px;
}
.drawer__footer {
  margin: 80px 0 0 20px;
}
</style>
